package cn.netty.example1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title:Client</p>
 * <p>Description:Netty客户端</p>
 * @version V1.0
 * @author ZhiPeng_Chen
 * @date: 2018/10/26
 */
public class Client {

    private EventLoopGroup clientGroup;

    private Bootstrap clientBoot;

    public Client(){
        init();
    }

    private void init(){
        clientGroup = new NioEventLoopGroup();
        clientBoot = new Bootstrap();

        //绑定线程组
        clientBoot.group(clientGroup);
        clientBoot.channel(NioSocketChannel.class);
    }


    public ChannelFuture doRequest(String host, int port, final ChannelHandler...channelHandler) throws InterruptedException {

        this.clientBoot.handler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(channelHandler);
            }

        });

        /**
         * 客户端建立连接
         */
        ChannelFuture future = this.clientBoot.connect(host, port).sync();

        return future;
    }


    /**
     * 回收资源
     */
    public void release(){
        this.clientGroup.shutdownGracefully();
    }




    public static void main(String[] args) {
        Client client = null;
        ChannelFuture future = null;
        try {
            client = new Client();
            future = client.doRequest("localhost", 8080, new ClientHandler());

            Scanner input = null;
            while (true){
                input = new Scanner(System.in);

                String inputStr = input.nextLine();

                //条件满足触发监听器
                if ("exit".equals(inputStr)){
                    //addListener 添加监听
                    //ChannelFutureListener.CLOSE 关闭监听器
                    future.channel().writeAndFlush(Unpooled.copiedBuffer(inputStr.getBytes("UTF-8")))
                            .addListener(ChannelFutureListener.CLOSE);
                    break;
                }

                future.channel().writeAndFlush(Unpooled.copiedBuffer(inputStr.getBytes("UTF-8")));
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());

        }finally {
            if (null !=future){
                try {
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (null != client){
                client.release();
            }
        }
    }

}
